package com.daniel.juc.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * 统一任务
 *
 * @author Daniel
 * @version V1.0
 * @date 2020/5/25 10:58
 */
public class Test {
	public static void main(String[] args) {
		test1(); // 9475
		test2(); // 6822
		test3(); // 408
	}

	/**
	 * 普通方法
	 */
	public static void test1() {
		Long sum = 0L;
		Long start = System.currentTimeMillis();
		for (Long i = 1L; i <= 10_0000_0000; i++) {
			sum += i;
		}
		Long end = System.currentTimeMillis();
		System.out.println("SUM=" + sum + " 时间 " + (end - start));
	}

	/**
	 * ForkJoin方法
	 */
	public static void test2() {
		Long start = System.currentTimeMillis();

		ForkJoinPool forkJoinPool = new ForkJoinPool();
		ForkJoinTask<Long> task = new ForkJoinDemo(0L, 10_0000_0000L);
		ForkJoinTask<Long> submit = forkJoinPool.submit(task);

		Long sum = null;
		try {
			sum = submit.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		Long end = System.currentTimeMillis();
		System.out.println("SUM=" + sum + " 时间 " + (end - start));
	}

	/**
	 * Stream并行流
	 */
	public static void test3() {
		Long start = System.currentTimeMillis();
		Long sum = LongStream.rangeClosed(1L, 10_0000_0000L)
				.parallel()
				.reduce(0, Long::sum);
		Long end = System.currentTimeMillis();
		System.out.println("SUM=" + sum + " 时间 " + (end - start));
	}

}
